import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class Udpserver {
    private DatagramSocket socket=null;
//手动指定服务器的端口
    public Udpserver(int port) throws SocketException {
        socket=new DatagramSocket(port);
    }
    //启动服务器
    public  void start() throws IOException {
        System.out.println("启动服务器");
        while(true){
            //读取请求
            DatagramPacket requestPack=new DatagramPacket(new byte[1024],1024);
            //接收请求
            socket.receive(requestPack);
            String request =new String(requestPack.getData(),0,requestPack.getLength(),"UTF-8");
            //根据请求构成响应
            String response=process(request);
            //把响应返回到客户端
            DatagramPacket responsePack = new DatagramPacket(response.getBytes(), response.getBytes().length,
                    requestPack.getSocketAddress());
        //requestPack.getSocketAddress()服务器的ip地址的端口号
            socket.send(responsePack);
            System.out.printf("[%s:%d] req: %s, resp: %s\n",
                    requestPack.getAddress().toString(), requestPack.getPort(), request, response);
        }
    }
    public  String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        Udpserver udpserver=new Udpserver(9090);
        udpserver.start();
    }
}
